package com.zxy.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zxy.basic.dao.TenantUserMapper;
import com.zxy.basic.model.entity.TenantUser;
import com.zxy.basic.model.vo.SyncTenantUserVO;
import com.zxy.basic.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: mybatis-study
 * @description:
 * @author: zhangxiaoyang
 * @date: 2020/6/17 3:51 下午
 **/
@Service
@Slf4j
public class IndexServiceImpl implements IndexService {

    @Autowired
    private TenantUserMapper tenantUserMapper;

    @Override
    public void updateTenantUser(SyncTenantUserVO tenantUserVO) {
        if (tenantUserVO == null) {
            log.error("同步的租户用户为空");
            return;
        }
        log.info("同步租户用户到索引表: {}", tenantUserVO);
        TenantUser exist = tenantUserMapper.selectOne(new LambdaQueryWrapper<TenantUser>().eq(TenantUser::getTenantId, tenantUserVO.getTenantId())
                                                                                          .eq(TenantUser::getUserId, tenantUserVO.getUserId())
                                                                                          .orderByDesc(TenantUser::getId));
        log.info("是否存在用户:{}", exist);
        TenantUser tenantUser = new TenantUser();
        BeanUtils.copyProperties(tenantUserVO, tenantUser);
        if (exist != null) {
            tenantUser.setId(exist.getId());
//            tenantUserMapper.updateById(tenantUser);
            tenantUserMapper.update(tenantUser, new UpdateWrapper<TenantUser>().lambda()
                                                                                     .set(TenantUser::getMobile,tenantUserVO.getMobile())
                                                                                     .set(TenantUser::getPersonName,tenantUserVO.getPersonName())
                                                                                     .set(TenantUser::getTenantViewName,tenantUserVO.getTenantViewName())
                                                                                     .eq(TenantUser::getId, exist.getId()));
        } else {
            tenantUserMapper.insert(tenantUser);
        }
        log.info("同步租户用户成功");
    }
}
